import 'dart:typed_data';

import 'package:fbdplugin/plugin_constant_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';

import 'map_utils.dart';

import 'dart:ui' as ui;

class BDMapPage extends StatefulWidget {

  Color? appBarBg;
  double? appBarElevation;
  dynamic sendLatitude;
  dynamic sendLongitude;
  dynamic sendAddress;

  dynamic receiveLatitude;
  dynamic receiveLongitude;
  dynamic receiveAddress;

  BDMapPage({Key? key,
    this.appBarBg,this.appBarElevation,this.sendAddress,this.sendLatitude,this.sendLongitude,
    this.receiveAddress,this.receiveLatitude,this.receiveLongitude,
  }) : super(key: key);

  @override
  State<BDMapPage> createState() => _BDMapPageState();
}

class _BDMapPageState extends State<BDMapPage> {
  BMFMapController? mapController;

  @override
  void initState() {
    widget.sendLatitude = (widget.sendLatitude==null||widget.sendLatitude==''||widget.sendLatitude=='null')?'0':widget.sendLatitude;
    widget.sendLongitude = (widget.sendLongitude==null||widget.sendLongitude==''||widget.sendLongitude=='null')?'0':widget.sendLongitude;
    widget.receiveLatitude = (widget.receiveLatitude==null||widget.receiveLatitude==''||widget.receiveLatitude=='null')?'0':widget.receiveLatitude;
    widget.receiveLongitude = (widget.receiveLongitude==null||widget.receiveLongitude==''||widget.receiveLongitude=='null')?'0':widget.receiveLongitude;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: widget.appBarElevation??0,
        backgroundColor: widget.appBarBg??Color(0xFFB3895D),
        title: Text(
          '地图',
          style: TextStyle(
              color: Colors.white
          ),
        ),
        actions: [
          (!isShowNav())?SizedBox(width: 0,):
          MaterialButton(onPressed: ()=>toNav(),child: Text('发起导航',style: TextStyle(color: Colors.white),),)
        ],
      ),
      body: (!isShowMap())?Container(
        child: Center(
          child: Text(
              '暂未获取到地图信息~'
          ),
        ),
      ):
      Container(
        width: MediaQuery.of(context).size.width,
        // height: PxUtils.screenHeight-PxUtils.statusBarHeight,
        child: BMFMapWidget(
          onBMFMapCreated: (BMFMapController mapController)=>bMFMapCreated(mapController),
          mapOptions: BMFMapOptions(
              center: BMFCoordinate(double.parse('${widget.sendLatitude}'), double.parse('${widget.sendLongitude}')),
              zoomLevel: 18,
              mapPadding: BMFEdgeInsets(left: 30, top: 0, right: 30, bottom: 0)),
        ),
      ),
    );
  }

  bMFMapCreated(BMFMapController bMapController) {
    try{
      print('onBMFMapCreated-->0 bMapController=bMapController');
      mapController = bMapController;
      mapController?.showUserLocation(true);
      //显示起止位置
      showLocation();
    }catch(e){
      print('onBMFMapCreated-->e=${e.toString()}');
    }
  }

  void showLocation() async{
    /// 创建BMFMarker
    try{
      // BMFMarker marker = BMFMarker(
      //   position: BMFCoordinate(double.parse(latitude??'0'), double.parse(longitude??'0')),
      //   title: 'flutterMaker',
      //   identifier: 'flutter_marker',
      //   icon: DrawableUtils.icon_location,
      //   scaleX: 0.5,
      //   scaleY: 0.5,
      // );
      // /// 添加Marker
      // mapController?.addMarker(marker);
      // mapController?.setCenterCoordinate(BMFCoordinate(double.parse(latitude??'0'),
      //     double.parse(longitude??'0')), true, animateDurationMs: 1000);
      print('onBMFMapCreated,addPoints-->send-->latitude=${widget.sendLatitude},longitude=${widget.sendLongitude}');
      print('onBMFMapCreated,addPoints-->recieve-->latitude=${widget.receiveLatitude},longitude=${widget.receiveLongitude}');
      //添加起止点
      if((widget.sendLatitude!='0')&&(widget.sendLongitude!='0')){
        // widget.sendLatitude = (widget.sendLatitude==null||widget.sendLatitude==''||widget.sendLatitude=='null')?'0':widget.sendLatitude;
        // widget.sendLongitude = (widget.sendLongitude==null||widget.sendLongitude==''||widget.sendLongitude=='null')?'0':widget.sendLongitude;
        // List bd09Nums = GpsUtil.gcj02_To_Bd09(double.parse(sendLatitude),double.parse(sendLongitude));
        List bd09Nums = [double.parse('${widget.sendLatitude}'),double.parse('${widget.sendLongitude}')];
        double latitude = bd09Nums[0];
        double longitude = bd09Nums[1];
        print('addPoints-->latitude=$latitude,longitude=$longitude');
        try{
          final ByteData assetImageBytes = await rootBundle.load('${PluginConstantUtil.img_base_url}/icon_start_local.png');
          final Uint8List assetImageData = assetImageBytes.buffer.asUint8List();
          BMFMarker marker = BMFMarker(
            position: BMFCoordinate(latitude, longitude),
            title: 'flutterMaker',
            identifier: 'flutter_marker',
            iconData: assetImageData,
            scaleX: 1,
            scaleY: 1,
          );
          /// 添加Marker
          mapController?.addMarker(marker);
          mapController?.setCenterCoordinate(BMFCoordinate(bd09Nums[0],bd09Nums[1]), true, animateDurationMs: 1000);

          mapController?.setVisibleMapRectWithPadding(
              visibleMapBounds: BMFCoordinateBounds(
                northeast: BMFCoordinate(bd09Nums[0],bd09Nums[1]),
                southwest: BMFCoordinate(bd09Nums[0],bd09Nums[1]),
              ),
              insets: EdgeInsets.all(20),
              animated: false
          );
        }catch(e){
          print('showLocation-->e=$e');
        }

      }

      if(('${widget.receiveLatitude}'!='0')&&('${widget.receiveLongitude}'!='0')){
        List bd09Nums = [double.parse('${widget.receiveLatitude}'),double.parse('${widget.receiveLongitude}')];
        double latitude = bd09Nums[0];
        double longitude = bd09Nums[1];
        print('addPoints-->latitude=$latitude,longitude=$longitude');
        try{
          final ByteData assetImageBytes = await rootBundle.load('${PluginConstantUtil.img_base_url}/icon_end_local.png');
          final Uint8List assetImageData = assetImageBytes.buffer.asUint8List();
          BMFMarker marker = BMFMarker(
            position: BMFCoordinate(latitude, longitude),
            title: 'flutterMaker',
            identifier: 'flutter_marker',
            iconData: assetImageData,
            scaleX: 1,
            scaleY: 1,
          );
          /// 添加Marker
          mapController?.addMarker(marker);
          mapController?.setCenterCoordinate(BMFCoordinate(bd09Nums[0],bd09Nums[1]), true, animateDurationMs: 1000);

          mapController?.setVisibleMapRectWithPadding(
              visibleMapBounds: BMFCoordinateBounds(
                northeast: BMFCoordinate(bd09Nums[0],bd09Nums[1]),
                southwest: BMFCoordinate(bd09Nums[0],bd09Nums[1]),
              ),
              insets: EdgeInsets.all(20),
              animated: false
          );
        }catch(e){
          print('showLocation-->e=$e');
        }
      }
      if(
      (('${widget.sendLatitude}'!='0')&&('${widget.sendLongitude}'!='0'))
          &&(('${widget.receiveLatitude}'!='0')&&('${widget.receiveLongitude}'!='0'))
      ){
        // List sendbd09Nums = GpsUtil.gcj02_To_Bd09(double.parse(sendLatitude),double.parse(sendLongitude));
        // List receivebd09Nums = GpsUtil.gcj02_To_Bd09(double.parse(receiveLatitude),double.parse(receiveLongitude));
        List sendbd09Nums = [double.parse('${widget.sendLatitude}'),double.parse('${widget.sendLongitude}')];
        List receivebd09Nums = [double.parse('${widget.receiveLatitude}'),double.parse('${widget.receiveLongitude}')];
        mapController?.setVisibleMapRectWithPadding(
            visibleMapBounds: BMFCoordinateBounds(
              northeast: BMFCoordinate(sendbd09Nums[0],sendbd09Nums[1]),
              southwest: BMFCoordinate(receivebd09Nums[0],receivebd09Nums[1]),
            ),
            insets: EdgeInsets.all(20),
            animated: false
        );
      }

    }catch(e){
      print('showLocation-->e=$e');
    }
  }
  bool isShowNav(){
    if((widget.sendLatitude==null)||(widget.sendLatitude=='null')||(widget.sendLatitude=='')
        ||(widget.sendLatitude==0)||(double.parse('${widget.sendLatitude}')==0)){
      return false;
    }
    if((widget.sendLongitude==null)||(widget.sendLongitude=='null')||(widget.sendLongitude=='')
        ||(widget.sendLongitude==0)||(double.parse('${widget.sendLongitude}')==0)){
      return false;
    }
    if((widget.receiveLatitude==null)||(widget.receiveLatitude=='null')||(widget.receiveLatitude=='')
        ||(widget.receiveLatitude==0)||(double.parse('${widget.receiveLatitude}')==0)){
      return false;
    }
    if((widget.receiveLongitude==null)||(widget.receiveLongitude=='null')||(widget.receiveLongitude=='')
        ||(widget.receiveLongitude==0)||(double.parse('${widget.receiveLongitude}')==0)){
      return false;
    }
    return true;
  }
  bool isShowMap(){
    if((widget.sendLatitude==null)||(widget.sendLatitude=='null')||(widget.sendLatitude=='')
        ||(widget.sendLatitude==0)||(double.parse('${widget.sendLatitude}')==0)){
      return false;
    }
    if((widget.sendLongitude==null)||(widget.sendLongitude=='null')||(widget.sendLongitude=='')
        ||(widget.sendLongitude==0)||(double.parse('${widget.sendLongitude}')==0)){
      return false;
    }

    return true;
  }
  toNav() {
    if(!isShowNav())return;
    MapUtils.goMap(widget.receiveAddress, widget.receiveLatitude, widget.receiveLongitude);
  }
}
